package org.linlinjava.litemall.admin.util;

import org.apache.ibatis.mapping.MappedStatement;
import org.linlinjava.litemall.db.util.MerchantPermission;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class MerchantPermissionUtils {
    /**
     * 根据 StatementHandler 获取 注解对象
     * @author dujunli
     * @date 2020-03-17
     */
    public static MerchantPermission getPermissionByDelegate(MappedStatement mappedStatement){
        MerchantPermission merchantPermission = null;
        try {
            String id = mappedStatement.getId();
            String className = id.substring(0, id.lastIndexOf("."));
            String methodName = id.substring(id.lastIndexOf(".") + 1, id.length());
            final Class cls = Class.forName(className);

            if(cls.isAnnotationPresent(MerchantPermission.class)){
                merchantPermission = (MerchantPermission) cls.getAnnotation(MerchantPermission.class);
            }

            final Method[] method = cls.getMethods();
            for (Method me : method) {
                if (me.getName().equals(methodName) && me.isAnnotationPresent(MerchantPermission.class)) {
                    merchantPermission = me.getAnnotation(MerchantPermission.class);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return merchantPermission;
    }
}
